package com.lovely3x.paymentlibrary.lianlian;

import android.os.Handler;
import android.os.Message;

import com.lovely3x.common.managements.pay.IPayCallBack;
import com.lovely3x.common.managements.pay.InitHook;
import com.lovely3x.common.managements.pay.PayAction;
import com.lovely3x.common.managements.pay.PayRequest;
import com.lovely3x.common.managements.pay.PaymentManager;
import com.lovely3x.paymentlibrary.alipay.AliPayPayRequest;
import com.lovely3x.paymentlibrary.lianlian.utils.BaseHelper;
import com.lovely3x.paymentlibrary.lianlian.utils.Constants;
import com.lovely3x.paymentlibrary.lianlian.utils.LianLianPayRequest;
import com.lovely3x.paymentlibrary.lianlian.utils.MobileSecurePayer;

import org.json.JSONObject;

/**
 * Created by handsome-Bob on 2017/7/12.
 * <p>
 * 连连支付
 */
public class LianLianPayAction implements PayAction, InitHook<PaymentManager> {

    public static final LianLianPayAction INSTANCE = new LianLianPayAction();

    private Handler mHandler = createHandler();

    private Handler createHandler() {
        return new Handler() {
            public void handleMessage(Message msg) {
                String strRet = (String) msg.obj;
                switch (msg.what) {
                    case Constants.RQF_PAY: {
                        JSONObject objContent = BaseHelper.string2JSON(strRet);
                        String retCode = objContent.optString("ret_code");
                        if (Constants.RET_CODE_SUCCESS.equals(retCode)) {
                            PaymentManager.getInstance().notifyPayResult(IPayCallBack.PayMethod.LianLainPay, IPayCallBack.PayResult.Successful);
                        } else {
                            PaymentManager.getInstance().notifyPayResult(IPayCallBack.PayMethod.LianLainPay, IPayCallBack.PayResult.Fail);
                        }
                    }
                    break;
                }
                super.handleMessage(msg);
            }
        };
    }

    @Override
    public void onInit(PaymentManager paymentManager) {
        paymentManager.registerPayAction(INSTANCE);
    }

    /**
     * @param payRequest 支付请求
     * @param payMethod  支付方式
     */
    @Override
    public boolean pay(PayRequest payRequest, IPayCallBack.PayMethod payMethod) {
        if (payMethod == IPayCallBack.PayMethod.LianLainPay && payRequest instanceof LianLianPayRequest) {
            MobileSecurePayer msp = new MobileSecurePayer();
            msp.pay(payRequest.getSign(), mHandler, Constants.RQF_PAY, ((LianLianPayRequest) payRequest).mActivity, false);
            return true;
        }
        return false;
    }
}
